<script setup>
import router from "@/router/index.js";
import {useAppStore} from "@/store/app.js";
import defaultSettings from "@/settings";
import AuthAPI from '@/api/auth/index.js'

onMounted(() => {
  getCaptcha()
})

const getCaptcha = () => {
  AuthAPI.getCaptcha().then(res => {
    console.log(res)
    captcha.value = res.img
    dataForm.captchaKey = res.key
  })
}
const captcha = ref('')

const appStore = useAppStore();
const currentRoute = useRoute();

const _logion = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      AuthAPI.login(dataForm).then(data => {
        appStore.setToken(data.token)
        const redirect = currentRoute.query?.redirect ? currentRoute.query?.redirect : '/';
        router.push(redirect)
      })
    }
  })
}

const formRef = ref()
const dataForm = reactive({
  account: '',
  password: '',
  captcha: '',
  captchaKey: '',
})
const rules = reactive({
  account: [{required: true, message: '必填项', trigger: 'blur'}],
  password: [{required: true, message: '必填项', trigger: 'blur'}],
  captcha: [{required: true, message: '必填项', trigger: 'blur'}],
})
</script>

<template>
  <div style="height: 100vh;display: flex;align-items: center;justify-content: center;">
    <el-card style="width: 360px">
      <template #header>
        <div style="text-align: center;">
          {{ defaultSettings.title }}
        </div>
      </template>
      <el-form ref="formRef" :model="dataForm" :rules="rules" label-position="right" label-width="auto">
        <el-form-item label="账号" prop="account">
          <el-input v-model="dataForm.account" size="large"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="dataForm.password" size="large" type="password" show-password/>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-input v-model="dataForm.captcha" size="large" class="captcha" >
            <template #suffix>
               <el-image @click="getCaptcha" style="width: 100px; height: 100%;cursor: pointer;border-radius: var(--el-input-border-radius, var(--el-border-radius-base));" :src="captcha" fit="fill" />
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div style="display: flex;align-items: center;justify-content: space-between;">
        <div></div>
        <el-button type="primary" @click="_logion(formRef)">登录</el-button>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
  .captcha {
    :deep(.el-input__wrapper) {
      padding-right: 1px !important;
    }
  }
</style>